import requests
import os


class WeComRobotSender:
    def __init__(self, webhook_url):
        """
        初始化企业微信机器人发送器  群发消息
        :param webhook_url: 机器人Webhook地址（含签名）
        """
        self.webhook_url = webhook_url
        self.base_url = "https://qyapi.weixin.qq.com"

    def send_text_message(self, content):
        """发送文本消息"""
        data = {
            "msgtype": "text",
            "text": {"content": content}
        }
        return self._send_request(data)

    def upload_file(self, file_path):
        """上传文件到企业微信临时素材"""
        if not os.path.exists(file_path):
            print(f"文件不存在: {file_path}")
            return None
        # 企业微信文件上传限制（通常≤20MB ），这里简单校验
        file_size = os.path.getsize(file_path)
        if file_size > 20 * 1024 * 1024:
            print("文件超过20MB限制，上传失败")
            return None

        # 从Webhook解析access_token和机器人key（企业微信机器人上传文件需特殊处理 ）
        # Webhook格式：https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxx
        # 实际需拆分出 key 用于文件上传接口
        key = self.webhook_url.split("key=")[-1]
        upload_url = f"{self.base_url}/cgi-bin/webhook/upload_media?key={key}&type=file"

        with open(file_path, 'rb') as f:
            files = {'media': f}
            response = requests.post(upload_url, files=files)
            result = response.json()
            if result.get("errcode") == 0:
                print("文件上传成功")
                return result.get("media_id")
            else:
                print(f"文件上传失败: {result.get('errmsg')}")
                return None

    def send_file_message(self, file_path):
        """发送文件消息"""
        media_id = self.upload_file(file_path)
        if not media_id:
            return False
        data = {
            "msgtype": "file",
            "file": {"media_id": media_id}
        }
        return self._send_request(data)

    def _send_request(self, data):
        """通用请求发送方法"""
        try:
            response = requests.post(self.webhook_url, json=data)
            result = response.json()
            if result.get("errcode") == 0:
                print("消息发送成功")
                return True
            else:
                print(f"消息发送失败: {result.get('errmsg')}")
                return False
        except Exception as e:
            print(f"请求出错: {str(e)}")
            return False


if __name__ == "__main__":
    # 替换为你的企业微信机器人Webhook地址（在群机器人设置中复制 ）
    WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8bb2fb85-657f-4f06-867d-ad386f2b763b"

    sender = WeComRobotSender(WEBHOOK_URL)

    # 发送文本消息
    sender.send_text_message("这是企业微信机器人发送的文本消息！[色]")

    # 发送文件（替换为实际文件路径 ）
    sender.send_file_message("a.txt")
    sender.send_file_message("feishu.docx")


    # 企业微信机器人